package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * servlet类加载器
 */
public class ClazzLoader extends ClassLoader {

    private byte[] getData(String path) {
        File file = new File(path);
        if (file.exists()) {
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(file);
                out = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = in.read(buffer)) != -1) {
                    out.write(buffer, 0, size);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            return out.toByteArray();
        } else {
            return null;
        }


    }

    //类加载器可继承ClassLoader，然后需重写ClassLoader的findClass方法来加载外部类
    @Override
    protected Class<?> findClass(String basePath, String clazzName) {
        byte[] clazzBytes = getData(basePath);
        Class servlet_clazz = defineClass(clazzName, clazzBytes, 0, clazzBytes.length);
        return servlet_clazz;
    }

    public static void main(String[] args) {
        String fullpath = "/Users/kumashunmatsu/Desktop/拉勾/作业/2.1 tomcat/code/out/demo1/server/LagouServlet.class";
        String className="server.LagouServlet";

        ClazzLoader t=new ClazzLoader();
        Class<?> tt = t.findClass(fullpath, className);

        System.out.println("tt >> " + tt);

        List<Method> ms= Arrays.asList(tt.getMethods());
        ms.forEach(c -> System.out.println("method name: "+c.getName()));

    }


}
